package ru.gerunn.silent.server;

import java.io.IOException;

import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

import ru.gerunn.silent.common.Reader;
import ru.gerunn.silent.common.SSLSocketReader;
import ru.gerunn.silent.common.SSLSocketWriter;
import ru.gerunn.silent.common.Writer;
import ru.gerunn.silent.exception.SilentException;
import ru.gerunn.silent.exception.SilentReadMessageException;
import ru.gerunn.silent.message.Message;
import ru.gerunn.silent.user.User;

@SuppressWarnings("unused")
public class Session extends Thread {

	private SSLSocket socket;
	private Writer writer;
	private Reader reader;
	private Server server;
	private User user;
	private String id;

	public Session(SSLSocket socket, Server server) throws IOException {
		this.socket = socket;
		this.reader = new SSLSocketReader(socket);
		this.writer = new SSLSocketWriter(socket);
		this.server = server;
		this.id = socket.getSession().getId().toString();
	}

	public void run() {
		this.server.getSessions().put(this.id, this);
		Message message = null;
		try {
			while ((message = this.reader.read()) != null) {
				if (this.server.isLogToConsole()) {
					System.out.println(message.toString());
				}
				this.server.getMessageQueue().add(message);
			}
		} catch (SilentReadMessageException e) {
			System.out.println("'" + this.id + "' session terminated");
			this.server.removeSession(this.id);
			// e.printStackTrace();
		}
	}

	public Writer getWriter() {
		return this.writer;
	}

}
